<template>
  <div id="container">
    <!-- 顶部组件 -->
    <TopSearch @searchData="searchData"></TopSearch>

    <!-- 页面头部栏 -->
    <div id="header">
      <span>套餐列表</span>
      <el-button
        type="primary"
        icon="el-icon-plus"
        size="small"
        @click="addNewBundle = true"
        >新增套餐</el-button
      >
    </div>

    <!-- 点击新增按钮后的一级弹窗表单 -->
    <el-dialog
      title="新增套餐"
      :visible.sync="addNewBundle"
      v-if="addNewBundle"
    >
      <el-form :model="form">
        <el-row>
          <el-col :span="8">
            <el-form-item label="*套餐名称:" :label-width="formLabelWidth">
              <el-input
                v-model="form.name"
                autocomplete="off"
                style="width: 20rem"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="*价格:" :label-width="formLabelWidth">
              <el-input
                v-model="form.price"
                autocomplete="off"
                style="width: 20rem"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="*编号:" :label-width="formLabelWidth">
              <el-input
                v-model="form.sequence"
                autocomplete="off"
                style="width: 20rem"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="*套餐类别:" :label-width="formLabelWidth">
              <el-select
                v-model="form.type"
                placeholder="请选择套餐类别"
                style="width: 20rem"
              >
                <el-option label="套餐一" value="套餐一"></el-option>
                <el-option label="套餐二" value="套餐二"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态:" :label-width="formLabelWidth">
              <el-switch
                style="display: block; height: 4rem; line-height: 4rem"
                v-model="form.state"
                active-color="#13ce66"
              >
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="允许打折:" :label-width="formLabelWidth">
              <el-switch
                style="display: block; height: 4rem; line-height: 4rem"
                v-model="form.discoun"
                active-color="#13ce66"
              >
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="*图片:" :label-width="formLabelWidth">
              <el-upload
                class="avatar-uploader"
                action="http://49.235.240.193:8080/admin/upload/image"
                name="image"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="8"></el-col>
        </el-row>

        <!-- 下方表格 -->
        <el-row>
          <el-col :span="24">
            <el-table
              :data="selectedDish"
              border
              style="margin-top: 1rem; width: 100%"
            >
              <el-table-column label="序号" width="100" align="center">
                <template slot-scope="scope">{{ scope.row.id }}</template>
              </el-table-column>
              <el-table-column label="菜品名称" width="150" align="center">
                <template slot-scope="scope">{{ scope.row.name }}</template>
              </el-table-column>
              <el-table-column label="菜品编号" width="150" align="center">
                <template slot-scope="scope">{{ scope.row.dish_no }}</template>
              </el-table-column>
              <el-table-column label="价格" width="120" align="center">
                <template slot-scope="scope">{{ scope.row.price }}</template>
              </el-table-column>
              <el-table-column label="状态" width="120" align="center">
                <template slot-scope="scope">{{ scope.row.status }}</template>
              </el-table-column>
              <el-table-column label="数量" width="130" align="center">
                <template slot-scope="scope">{{ scope.row.quantity }}</template>
              </el-table-column>
              <!-- <el-table-column label="合计" align="center" width="80">
                <template slot-scope="scope">{{ scope.row.total }}</template>
              </el-table-column> -->
              <el-table-column label="操作" align="center">
                <el-button size="mini" @click="getDishTypeID('汤')"
                  >添加</el-button
                >
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addNewBundle = false">取 消</el-button>
        <el-button type="primary" @click="addNewPack">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 点击添加按钮后的二级弹窗表单 -->
    <el-dialog
      title="选择菜品"
      :visible.sync="addNewFood"
      width="40%"
      destroy-on-close
      close-on-press-escape
      v-if="addNewFood"
    >
      <div>
        <!-- 动态渲染类别标签栏 -->
        <el-row style="margin-top: 2rem">
          <el-tabs
            tab-position="left"
            style="height: 300px"
            @tab-click="getDishTypeID"
          >
            <el-tab-pane
              v-for="item in dishTypeTable"
              :key="item.id"
              :label="item.category"
            >
              <!-- 动态渲染商品 -->
              <el-radio-group v-model="checkDishList">
                <el-radio
                  v-for="item in dishFileTable"
                  :key="item.id"
                  :label="item.id"
                  border
                  size="medium"
                  style="margin-top: 1rem; margin-left: 0"
                  >{{ item.name }}
                </el-radio>
              </el-radio-group>
            </el-tab-pane>
          </el-tabs>
        </el-row>
        <el-row style="margin-top: 2rem"> </el-row>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="addNewFood = false">取 消</el-button>
        <el-button type="primary" @click="getCheckedDish">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 动态渲染页面表格内容 -->
    <el-table :data="tableData" border style="margin-top: 1rem; width: 100%">
      <el-table-column label="序号" width="120" align="center">
        <template slot-scope="scope">{{ scope.row.id }}</template>
      </el-table-column>
      <el-table-column label="套餐名称" width="200" align="center">
        <template slot-scope="scope">{{ scope.row.name }}</template>
      </el-table-column>
      <el-table-column label="编号" width="200" align="center">
        <template slot-scope="scope">{{ scope.row.sequence }}</template>
      </el-table-column>
      <el-table-column label="价格" width="150" align="center">
        <template slot-scope="scope">{{ scope.row.price }}</template>
      </el-table-column>
      <el-table-column label="状态" width="150" align="center">
        <template slot-scope="scope">{{ scope.row.state }}</template>
      </el-table-column>
      <el-table-column label="月销量" width="130" align="center">
        <template slot-scope="scope">{{ scope.row.volume }}</template>
      </el-table-column>
      <el-table-column label="数量" width="130" align="center">
        <template slot-scope="scope">{{ scope.row.quantity }}</template>
      </el-table-column>
      <el-table-column label="打折状态" align="center" width="250">
        <template slot-scope="scope">{{ scope.row.discoun }}</template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="editPack(scope.row.name, scope.row.id)"
            >查看</el-button
          >
          <el-button type="warning" size="mini" @click="editState(scope.row.id)"
            >出售状态</el-button
          >
          <el-button
            type="success"
            size="mini"
            @click="editDiscountState(scope.row.id)"
            >打折状态</el-button
          >
          <el-button type="danger" size="mini" @click="deletePack(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Page :totalCount="totalCount" @shareData="shareData"></Page>
  </div>
</template>

<script>
import TopSearch from "./../../components/common/search_2";
import Page from "./../../components/common/Pagination.vue";
export default {
  data() {
    return {
      input: "", //上方搜索框
      tableData: [], //初始化时渲染表格数据
      multipleSelection: [],
      dishTypeTable: [], //菜品类别
      dishFileTable: [], //菜品档案
      addNewBundle: false, //一级dialog开关
      addNewFood: false, //二级dialog开关
      checkDishList: [], //二级菜单中选中的菜品的id
      selectedDish: [],
      form: {
        //新建套餐表单的内容
        name: "",
        price: "",
        imageUrl: "",
        type: "",
        sequence: "",
        state: true,
        discoun: true,
        imge: "",
        quantity: 0,
        id: 0,
      },
      selectedDish: [
        //一级dialog下方表格
        {
          id: "",
          dish_no: "",
          name: "",
          price: "",
          status: "",
          quantity: "",
        },
      ],
      formLabelWidth: "80px",

      // 分页
      totalCount: 0,
      nowPage: 1,
      pageCount: 5,
    };
  },
  components: {
    TopSearch,
    Page,
  },
  created() {
    // 在页面创建时获取表格数据并渲染
    this.getPackList(this.nowPage, this.pageCount);
    // 获取菜品类别
    this.getDishType();
    // 获取菜品信息
    this.getDishFile();
  },
  methods: {
    // 分页
    shareData(v) {
      this.nowPage = v.nowPage;
      this.pageCount = v.pageCount;

      this.getPackList(this.nowPage, this.pageCount);
    },

    // 上传图片
    handleAvatarSuccess(res, file) {
      // console.log(this);
      console.log(res);
      this.form.imge = res.data;
      this.form.imageUrl = URL.createObjectURL(file.raw);
      console.log(this.form.imageUrl);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    // 获取套餐列表
    async getPackList(page, pageSize) {
      const { data: res } = await this.axios.post("/pack/listname", {
        page: page,
        pageSize: pageSize,
      });
      // console.log(res.data);
      this.tableData = res.data;
      this.totalCount = res.count;
    },

    // 删除单条数据
    async deletePack(vid) {
      const { data: res } = await this.axios.get("/pack/delete/" + vid);
      this.getPackList();
      // console.log(res);
    },

    // 添加新套餐
    async addNewPack() {
      // 隐藏添加窗口
      this.addNewBundle = false;
      // 条件判断转换按钮的值
      if (this.form.state == true) {
        this.form.state = "在售";
      } else {
        this.form.state = "暂停出售";
      }
      if (this.form.discoun == true) {
        this.form.discoun = "允许打折";
      } else {
        this.form.discoun = "原价出售";
      }
      // console.log(this.form)
      // console.log(this.selectedDish);
     
        const { data: res } = await this.axios.post("/pack/add", {
          name: this.form.name,
          price: this.form.price,
          type: this.form.type,
          sequence: this.form.sequence,
          state: this.form.state,
          discoun: this.form.discoun,
          count: this.selectedDish[0].quantity,
          dishFileFId: this.selectedDish[0].id,
          quantity: 100,
          id: 0,
          imge: this.form.imge,
          volume: 0,
        });
        // console.log(res);
      // console.log(this.form.id);
      // this.form.id += 1;
      this.getPackList();

      // 后端接口有问题,无法实现多个菜品绑定套餐的上传,为了实现查看功能,暂时使用本地存储的方式实现
      let arrid = [];
      let arrname = [];
      let arrdish_no = [];
      let arrprice = [];
      let arrstatus = [];
      let arrquantity = [];
      for (let i = 0; i < this.selectedDish.length - 1; i++) {
        arrid.push(this.selectedDish[i].id);
        arrname.push(this.selectedDish[i].name);
        arrdish_no.push(this.selectedDish[i].dish_no);
        arrprice.push(this.selectedDish[i].price);
        arrstatus.push(this.selectedDish[i].status);
        arrquantity.push(this.selectedDish[i].quantity);
      }
      sessionStorage.setItem("did", arrid);
      sessionStorage.setItem("dname", arrname);
      sessionStorage.setItem("dno", arrdish_no);
      sessionStorage.setItem("dprice", arrprice);
      sessionStorage.setItem("dstatus", arrstatus);
      sessionStorage.setItem("dquantity", arrquantity);
    },

    // 获取菜品类别
    async getDishType() {
      const { data: res } = await this.axios.post(
        "/dishesCategory/findCategory",
        {
          page: 1,
          pageSize: 999,
        }
      );
      this.dishTypeTable = res.data;
      // console.log(this.dishTypeTable);
    },

    // 获取菜品档案
    async getDishFile() {
      const { data: res } = await this.axios.post("/dishFile/list", {
        page: 1,
        pageSize: 999,
      });
      // console.log(res);
    },

    // 获取各类别的菜品名
    async getDishTypeID(tab) {
      this.addNewFood = true;
      // 点击标签 获得标签的名字
      let DishTypeName = tab.label;
      // console.log(DishTypeName);
      // 调用类别查询接口,通过名字查询类别的id
      const { data: res } = await this.axios.post("/dishesCategory/list", {
        name: DishTypeName,
      });
      // console.log(res.data);
      // 调用菜品查询接口,通过类别id查询菜品
      let dishTypeID = res.data[0].id;
      // console.log(dishTypeID);
      const { data: r } = await this.axios.post("/dishFile/list", {
        categoryName: dishTypeID,
      });
      // 存储数据
      this.dishFileTable = r.data;
      // console.log(this.dishFileTable);
    },

    // 获取选中菜品信息
    async getCheckedDish() {
      // addNewFood = false
      let did = this.checkDishList;
      // console.log(did);
      let addedDish = this.dishFileTable.filter((x) => x.id === did)[0];
      if (addedDish.status == 0) {
        addedDish.status = "停售";
      } else {
        addedDish.status = "在售";
      }
      // console.log(addedDish);
      // 调用库存接口查询菜品数量
      const { data: res } = await this.axios.get("/stock/" + did);
      // console.log(res.data);

      addedDish.quantity = res.data.stock;
      this.form.quantity = res.data.stock;
      this.form.dishFileFId = res.data.id;
      console.log(this.form.dishFileFId);
      // console.log(this.form.quantity);
      // console.log(addedDish);
      this.selectedDish.unshift(addedDish);
      this.addNewFood = false;
    },

    // 修改出售状态
    async editState(vid) {
      // console.log(vid);
      let addedPack = this.tableData.filter((x) => x.id === vid)[0];
      // console.log(addedPack.state);
      if (addedPack.state == "暂停出售") {
        const { data: res } = await this.axios.post(
          "/pack/state" + `?id=${vid}&state=在售`
        );
        this.getPackList();
        // console.log(res);
      }
      if (addedPack.state == "在售") {
        const { data: res } = await this.axios.post(
          "/pack/state" + `?id=${vid}&state=暂停出售`
        );
        this.getPackList();
        // console.log(res);
      }
    },

    // 修改打折状态
    async editDiscountState(vid) {
      // console.log(vid);
      let addedPack = this.tableData.filter((x) => x.id === vid)[0];
      // console.log(addedPack);
      if (addedPack.discoun == "原价出售") {
        const { data: res } = await this.axios.post(
          "/pack/discoun" + `?id=${vid}&discoun=允许打折`
        );
        this.getPackList();
        // console.log(res);
      }
      if (addedPack.discoun == "允许打折") {
        const { data: res } = await this.axios.post(
          "/pack/discoun" + `?id=${vid}&discoun=原价出售`
        );
        this.getPackList();
        // console.log(res);
      }
    },

    // 查看套餐详情
    async editPack(vname, vid) {
      this.addNewBundle = true;
      const { data: res } = await this.axios.post("/pack/listname", {
        name: vname,
      });
      console.log(res.data);
      let pack = res.data.filter((x) => x.id === vid)[0];
      console.log(pack);
      this.form.name = pack.name;
      this.form.price = pack.price;
      this.form.sequence = pack.sequence;
      this.form.imageUrl = pack.imge;
      this.form.type = pack.type;
      if (pack.state == "在售") {
        this.form.state = true;
      } else {
        this.form.state = false;
      }
      if (pack.discoun == "允许打折") {
        this.form.discoun = true;
      } else {
        this.form.discoun = false;
      }

      // 调用本地存储,渲染表格数据
      let did = sessionStorage.getItem("did").split(",");
      let dname = sessionStorage.getItem("dname").split(",");
      let dno = sessionStorage.getItem("dno").split(",");
      let dprice = sessionStorage.getItem("dprice").split(",");
      let dstatus = sessionStorage.getItem("dstatus").split(",");
      let dquantity = sessionStorage.getItem("dquantity").split(",");
      for (let i = 0; i < did.length; i++) {
        this.selectedDish[i].id = did[i];
        this.selectedDish[i].name = dname[i];
        this.selectedDish[i].dish_no = dno[i];
        this.selectedDish[i].price = dprice[i];
        this.selectedDish[i].status = dstatus[i];
        this.selectedDish[i].quantity = dquantity[i];
        console.log(this.selectedDish);
      }
      console.log(dstatus);
    },

    // 搜索功能
    searchData(v) {
      this.tableData = v.data;
      this.totalCount = v.count;
      // console.log(v);
    },
  },
};
</script>

<style lang="less" scoped>
#container {
  font-size: 1.5rem;
  vertical-align: center;
}

#header {
  margin-top: 1rem;
  height: 3rem;
  line-height: 3rem;
  background-color: lightgray;
  padding: 1.5rem;
  & > button {
    float: right;
    margin-left: 2rem;
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed black !important;
  border-radius: 6px !important;
  cursor: pointer !important;
  position: relative !important;
  overflow: hidden !important;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff !important;
}

.avatar-uploader-icon {
  font-size: 20px !important;
  color: #8c939d !important;
  width: 12rem !important;
  height: 100px !important;
  line-height: 100px !important;
  text-align: center !important;
}

.avatar {
  width: 10rem !important;
  height: 10rem !important;
  display: block !important;
}
</style>